package cn.itrip.biz.controller;

import cn.itrip.biz.service.itripHotelOrder.ItripHotelOrderService;
import cn.itrip.biz.service.itripHotelRoom.ItripHotelRoomService;
import cn.itrip.biz.service.itripHotelTempStore.ItripHotelTempStoreService;
import cn.itrip.biz.service.itripTradeEnds.ItripTradeEndsService;
import cn.itrip.common.*;
import cn.itrip.dto.Dto;
import cn.itrip.pojo.*;
import cn.itrip.vo.order.*;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

@RestController  //Controller+responseBody
@RequestMapping(value = "/api/hotelorder")
@Api(value = "biz测试HotelOrderController",tags = "{biz测试HotelOrderController}")
public class HotelOrderController {

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private ItripHotelOrderService itripHotelOrderService;
    @Resource
    private ItripHotelRoomService itripHotelRoomService;
    @Resource
    private ItripTradeEndsService itripTradeEndsService;
    @Resource
    private ItripHotelTempStoreService itripHotelTempStoreService;

    /**
     * 生成订单前,获取预订信息
     */
    @ApiOperation(value = " 生成订单前,获取预订信息")
    @RequestMapping(value = "/getpreorderinfo", method = RequestMethod.POST, produces = "application/json")
    public Dto getpreorderinfo(@RequestBody ValidateRoomStoreVO vo, HttpServletRequest request) {
        try {
            //1.验证token
            String token = request.getHeader("token");
            if (token != null && redisUtils.exit(token)) {
                //表单信息的验证
                if (vo.getRoomId() == null || vo.getRoomId() == 0) {
                    return DtoUtil.returnFail("房间ID不能为空", "100511");
                }
                if (vo.getHotelId() == null || vo.getHotelId() == 0) {
                    return DtoUtil.returnFail("酒店ID不能为空", "100510");
                }
                if (vo.getCheckInDate().getTime() > vo.getCheckOutDate().getTime()) {
                    return DtoUtil.returnFail("入住时间不能大于退房时间", "100514");
                }
                //封装前端需要的实体类
                Dto dto = itripHotelOrderService.getValiDateRoomStore(vo);
                return dto;
            }
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常", "100513");
        }
    }

    /**
     * 修改订房日期验证是否有房
     */
    @ApiOperation(value = " 修改订房日期验证是否有房")
    @RequestMapping(value = "/getpersonalorderinfo", method = RequestMethod.POST, produces = "application/json")
    public Dto<Map<String, Boolean>> getpersonalorderinfo(@RequestBody ValidateRoomStoreVO vo, HttpServletRequest request) {
        try {
            //1.验证token
            String token = request.getHeader("token");
            if (token != null && redisUtils.exit(token)) {
                //表单信息的验证
                if (vo.getRoomId() == null || vo.getRoomId() == 0) {
                    return DtoUtil.returnFail("房间ID不能为空", "100511");
                }
                if (vo.getHotelId() == null || vo.getHotelId() == 0) {
                    return DtoUtil.returnFail("酒店ID不能为空", "100516");
                }
                if (vo.getCheckInDate().getTime() > vo.getCheckOutDate().getTime()) {
                    return DtoUtil.returnFail("入住时间不能大于退房时间", "100514");
                }
                //封装前端需要的实体类
                Dto dto = itripHotelOrderService.getValiDateRoomStore1(vo);
                return dto;
            }
            return DtoUtil.returnFail("token失效，请重登录", "100000 ");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常", "100517 ");
        }
    }

    /**
     * 根据订单ID查看个人订单详情
     */
    @ApiOperation(value = "  根据订单ID查看个人订单详情")
    @RequestMapping(value = "getpersonalorderinfo/{orderId}", method = RequestMethod.GET, produces = "application/json")
    public Dto getPersonaLorderInfo(@PathVariable Integer orderId, HttpServletRequest request) {
        try {
            //1.验证token
            String token = request.getHeader("token");
            if (token != null && redisUtils.exit(token)) {
                if (orderId == null) {
                    return DtoUtil.returnFail("请传递参数：orderId", "100529");
                }

                ItripPersonalHotelOrderVO roomVO = itripHotelOrderService.getItripHotelOrderById2(Long.valueOf(orderId));
                if (roomVO != null) {
                    return DtoUtil.returnDataSuccess(roomVO);
                }
                return DtoUtil.returnFail("没有查询到相应订单", "100533");
            }
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取个人订单房型信息错误", "100531");
        }
    }


    /**
     * 根据个人订单列表，并分页显示
     */
    @ApiOperation(value = " 根据个人订单列表，并分页显示")
    @RequestMapping(value = "/getpersonalorderlist", method = RequestMethod.POST, produces = "application/json")
    public Dto getPersonaLorderList(@RequestBody ItripSearchOrderVO vo, HttpServletRequest request) {
        try {

            //1.验证token
            String token = request.getHeader("token");
            if (token != null && redisUtils.exit(token)) {

//                if(EmptyUtils.isEmpty(vo.getEndDate()) || EmptyUtils.isEmpty(vo.getStartDate())){
//                    return DtoUtil.returnFail("预定时间不能为空", "100511");
//                }
                ItripUser itripUser = JSONObject.parseObject(redisUtils.getValue(token),ItripUser.class);

                vo.setUserId(itripUser.getId().toString());

                Page page = itripHotelOrderService.getItripHotelOrderListByMap(vo);

                return DtoUtil.returnDataSuccess(page);
            }
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取个人订单列表错误", "100503");
        }
    }

    /**
     * 生成订单
     */
    @ApiOperation(value = " 生成订单")
    @RequestMapping(value = "/addhotelorder", method = RequestMethod.POST, produces = "application/json")
    public Dto<Map<String, Object>> addHotelOrder(@RequestBody ItripAddHotelOrderVO vo, HttpServletRequest request) {
        try {
            //1.验证token
            String token = request.getHeader("token");
            if (token != null && redisUtils.exit(token)) {
                //表单信息的验证
                if (EmptyUtils.isEmpty(vo.getCheckInDate())) {
                    return DtoUtil.returnFail("入住时间不能为空", "100506");
                }
                if (EmptyUtils.isEmpty(vo.getCheckOutDate())) {
                    return DtoUtil.returnFail("退房时间不能为空", "100516");
                }
                if (EmptyUtils.isEmpty(vo.getCount())) {
                    return DtoUtil.returnFail("酒店数量不能为空", "100516");
                }
                if (EmptyUtils.isEmpty(vo.getHotelId())) {
                    return DtoUtil.returnFail("酒店ID不能为空", "100516");
                }
                if (EmptyUtils.isEmpty(vo.getHotelName())) {
                    return DtoUtil.returnFail("酒店名称不能为空", "100516");
                }
//                if(EmptyUtils.isEmpty(vo.getId())){
//                    return DtoUtil.returnFail("修改需要的id不能为空", "100516");
//                }
                if (EmptyUtils.isEmpty(vo.getLinkUser())) {
                    return DtoUtil.returnFail("入住人不能为空", "100516");
                }
                if (EmptyUtils.isEmpty(vo.getOrderType())) {
                    return DtoUtil.returnFail("顶单类型不能为空", "100516");
                }
                if (EmptyUtils.isEmpty(vo.getRoomId())) {
                    return DtoUtil.returnFail("房间ID不能为空", "100514");
                }

                Dto dto = itripHotelOrderService.itriptxInsertItripHotelOrder(vo, token);
                return dto;
            }
            return DtoUtil.returnFail("token失效，请重登录", "100000 ");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常", "100517 ");
        }
    }

    /**
     * 根据订单ID获取订单信息
     */
    @ApiOperation(value = " 根据订单ID获取订单信息")
    @RequestMapping(value = "/queryOrderById/{orderId}", method = RequestMethod.GET, produces = "application/json")
    public Dto getpreorderinfo(@PathVariable Integer orderId, HttpServletRequest request) {
        try {
            ItripModifyHotelOrderVO itripModifyHotelOrderVO = new ItripModifyHotelOrderVO();
            //1.验证token
            String token = request.getHeader("token");
            if (token != null && redisUtils.exit(token)) {

                ItripHotelOrder itripHotelOrder = itripHotelOrderService.getItripHotelOrderById(orderId.longValue());
                if (itripHotelOrder != null) {
                    return DtoUtil.returnDataSuccess(itripHotelOrder);
                }

                return DtoUtil.returnFail("没有查询到相应订单", "100533");
            }
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常", "100534");
        }
    }

    /**
     * 根据订单ID查看个人订单详情-房型相关信息
     */
    @ApiOperation(value = " 根据订单ID查看个人订单详情-房型相关信息")
    @RequestMapping(value = "/getpersonalorderroominfo/{orderId}", method = RequestMethod.GET, produces = "application/json")
    public Dto getPersonalOrderRoominfo(@PathVariable String orderId, HttpServletRequest request) {
        try {
            //1.验证token
            String token = request.getHeader("token");
            if (token != null && redisUtils.exit(token)) {
                if (orderId == null) {
                    return DtoUtil.returnFail("请传递参数：orderId", "100529");
                }

                ItripPersonalOrderRoomVO roomVO = itripHotelOrderService.getItripPersonalOrderRoomByVo(Long.valueOf(orderId));

                if (roomVO != null) {
                    return DtoUtil.returnDataSuccess(roomVO);
                }
                return DtoUtil.returnFail("没有查询到相应订单", "100533");
            }
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取个人订单房型信息错误", "100531");
        }
    }

    /**
     * 修改订单的支付方式和状态
     */
    @ApiOperation(value = " 修改订单的支付方式和状态")
    @RequestMapping(value = "/updateorderstatusandpaytype", method = RequestMethod.POST, produces = "application/json")
    public Dto updateOrderStatusandpaytype(@RequestBody ItripModifyHotelOrderVO vo, HttpServletRequest request) {
        try {
            ItripModifyHotelOrderVO itripModifyHotelOrderVO = new ItripModifyHotelOrderVO();
            //1.验证token
            String token = request.getHeader("token");
            if (token != null && redisUtils.exit(token)) {
                //验证酒店id和支付方式是否为null
                if (EmptyUtils.isEmpty(vo.getId()) || EmptyUtils.isEmpty(vo.getPayType())) {
                    return DtoUtil.returnFail("不能提交空，请填写订单信息", "100523");
                }
                //查询酒店实体类
                Integer payType = itripHotelRoomService.getItripHotelRoomByPayType(vo.getId());

                System.out.println(payType);

                if (payType == 1) {
                    return DtoUtil.returnFail("对不起，此房间不支持线下支付", "100521");
                }

                Integer sf = itripHotelRoomService.itriptxModifyItripHotelRoomByPayType(vo.getId().toString(), "3");

                if (sf != 0) {
                    return DtoUtil.returnSuccess("修改成功");
                }

                return DtoUtil.returnFail("修改订单失败", "100522");

//                if (itripHotelRoomById.getPayType()==3){
//                    sf=itripHotelRoomService.itriptxModifyItripHotelRoomByPayType(map);
//                }else if (itripHotelRoomById.getPayType()==2){
//                    if (vo.getPayType()==1){
//                        return DtoUtil.returnFail("对不起，此房间不支持线下支付", "100521");
//                    }else{
//                        sf=itripHotelRoomService.itriptxModifyItripHotelRoomByPayType(map);
//                    }
//                }else{
//                    if (vo.getPayType()==3){
//                        return DtoUtil.returnFail("对不起，此房间不支持线下支付", "100521");
//                    }else{
//                        sf=itripHotelRoomService.itriptxModifyItripHotelRoomByPayType(map);
//                    }
//                }

            }
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("修改订单失败", "100522");
        }
    }

    /**
     * 扫描中间表,执行库存更新操作
     */
    @ApiOperation(value = "扫描中间表,执行库存更新操作")
    @RequestMapping(value = "/scanTradeEnd", method = RequestMethod.GET, produces = "application/json")
    public Dto scanTradeEnd() {
        try {
            List<ItripTradeEnds> ends = itripTradeEndsService.getItripTradeEnds();
            if (ends.size() == 0) {
                return DtoUtil.returnFail("没有查询到相应记录", "100535");
            }
            for (ItripTradeEnds end : ends) {
                itripHotelTempStoreService.updateItripHotelTempStore(end.getOrderNo());
            }
            return DtoUtil.returnSuccess("成功");
        } catch (Exception e) {
           return DtoUtil.returnFail("系统异常", "100536");
        }
    }

//    /**
//     * 支付成功后查询订单信息
//     */
//    @ApiOperation(value = "支付成功后查询订单信息")
//    @RequestMapping(value = "/querysuccessorderinfo/{id}", method = RequestMethod.POST, produces = "application/json")
//    public Dto querysSuccessorderInfo(@PathVariable Integer id, HttpServletRequest request){
//        try {
//            //1.验证token
//            String token = request.getHeader("token");
//            if (token != null && redisUtils.exit(token)) {
//                //验证酒店id和支付方式是否为null
//                if (EmptyUtils.isEmpty(id)) {
//                    return DtoUtil.returnFail("id不能为空", "100519");
//                }
//
//                return DtoUtil.returnFail("修改订单失败", "100522");
//            }
//            return DtoUtil.returnFail("token失效，请重登录", "100000");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return DtoUtil.returnFail("修改订单失败", "100520");
//        }
//    }


    //执行库存跟新的定时器
    @Scheduled(cron = "0 */10 * * * ?")
//    @Scheduled(cron = "*/10 * * * * ?")
    public void job() throws Exception {

        System.out.println(new Date()+"进入库存跟踪的定时器");

       //修改flag
        Map<String, Object> params = new HashMap<>();
        params.put("oldFlag", 0);
        params.put("flag", 1);

        Integer count = itripTradeEndsService.itriptxModifyItripTradeEndsFlag(params);

        //执行库存更新操作
        scanTradeEnd();


        // 修改flag
        params.put("oldFlag", 1);
        params.put("flag", 2);
        itripTradeEndsService.itriptxModifyItripTradeEndsFlag(params);
    }

    //入住时间判断是否已过期
    @Scheduled(cron = "0 1/60 * * * ?")
    public void changeOrderToComment() throws Exception {
        System.out.println(new Date()+"入住时间判断是否已过期");
        try {
            itripHotelOrderService.changeOrderToComment();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
